package com.bana.fvs.app.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.bana.fvs.app.common.ConstantsField;
import com.bana.fvs.app.main.entity.UserInfoBean;
import com.wei.commonlibrary.utils.SPUtils;

/**
 * Author : yanftch
 * Date : 2018/2/6
 * Time : 14:16
 * Desc : 登录信息保存
 */

public class UserInfoUtils {
    private volatile static UserInfoUtils instance;
    private UserInfoBean user;
    private String mToken;

    public static UserInfoUtils getInstance(){
        if (null == instance){
            synchronized (UserInfoBean.class){
                if (null == instance){
                    instance  = new UserInfoUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 缓存userinfo下次免登录
     *
     * @param context
     * @param user
     */
    public void saveUserInfo(Context context, UserInfoBean user) {
        SPUtils.saveObject(context, ConstantsField.USER, user);
        instance = getInstance();
        setUser(user);
    }

    /**
     * 只在当前状态下缓存，如果推出则清空，下次继续登录
     *
     * @param user
     */
    public void setUser(UserInfoBean user) {
        this.user = user;
        this.mToken = user.getToken();
    }

    public UserInfoBean getUserInfo(Context context) {
        getInstance();
        if (user == null) {
            UserInfoBean user = SPUtils.getObject(context, ConstantsField.USER, UserInfoBean.class);
            instance.user = user;
        }
        return instance.user;
    }

    public boolean isSavaInfo(Context context) {
        UserInfoBean user = SPUtils.getObject(context, ConstantsField.USER, UserInfoBean.class);
        return user != null;
    }

    public boolean getUserState(Context context) {
        return SPUtils.getBooleanData(context, ConstantsField.ISSAVA);
    }

    private static final String DEBUG_TAG = "debug_UserInfoUtils";
    public boolean isLogin(Context context) {
        Log.e(DEBUG_TAG, "74 ,isLogin:  = " + (getUserInfo(context) == null));
        return /*(user != null && mToken != null) ||*/ getUserInfo(context) != null;
    }

    public String getToken(Context context) {
        /**
         * 测试代码
         */
//        return "1";
        if (!TextUtils.isEmpty(mToken)) {
            return mToken;
        }
        if (user == null) {
            boolean savaInfo = isSavaInfo(context);
            if (savaInfo) {
                UserInfoBean user = SPUtils.getObject(context, ConstantsField.USER, UserInfoBean.class);
                this.user = user;
            }
        }
        if(user == null){
            return null;
        }
        String token = user.getToken();
        this.mToken = token;
        return token;
    }

    public void clearCache(Context context) {
        SPUtils.removeData(context, ConstantsField.USER);
        instance.user = null;
        mToken = null;
    }
}
